function getDisplaySeverity(a) {
    var sev = a.severity;
    sev = (sev > 1) ? ((sev < 5) ? sev : 5) : 1;
    return sev;
}

function formatAlert(a) {
    var sev = getDisplaySeverity(a);

    var flashing = !initial && !uids[a.uid + '-' + a.severity];
    var s = '<div class="alert severity-' + sev + ((flashing) ? ' flashing' : '') + '"><img src="/assets/icons/severity-' + sev + '.png" alt="Severity ' + sev + '"><h3>' + a.host + '</h3><p>' + a.alert + '</p>';

    if (a.value) {
        s += '<span class="value">' + a.value + '</span>';
    }
    s += '</div>';
    return s
}

var uids = {};
var initial = true;

function updatePage(data, textStatus, xhr) {
    var html = '';
    var severities = [0, 0, 0, 0, 0];

    var lastsev = -1;
    for (a in data) {
        var a = data[a];
        var sev = getDisplaySeverity(a);
        severities[sev - 1]++;

        if (sev != lastsev) {
            if (lastsev != -1) {
                html += '</div>';
            }
            lastsev = sev;
            html += '<div class="severity-group" id="severity-' + sev + '">';
        }
        
        html += formatAlert(a);
    }

    if (lastsev != -1) {
        html += '</div>';
    } else html = '<p id="okay"><em>All metrics are within standard parameters, Captain.</em></p>';

    window.uids = {};
    for (a in data) {
        window.uids[data[a].uid + '-' + data[a].severity] = true;
    }
    initial = false;

    $('#alerts').html(html);
    if ($('.flashing').size()) {
        startFlashing();
    }
    
    html = '';
    var haveicon = false;
    var highest_sev = null;
    for (var sev = 1; sev <= 5; sev++) {
        var count = severities[sev - 1];
        if (count) {
            if (highest_sev == null) {
                highest_sev = sev;
                $('#icon').remove();
                $('head').append('<link rel="shortcut icon" href="/assets/icons/severity-' + sev + '.png">');
            }
            html += '<div class="summary summary-' + sev + '"><a href="#severity-' + sev + '"><img src="/assets/icons/severity-' + sev + '.png" alt="Severity ' + sev +'">' + count + '</a></div>\n';
        } else {
            html += '<div class="summary summary-empty summary-' + sev + '"><img src="/assets/icons/severity-' + sev + '.png" alt="Severity ' + sev +'">' + count + '</div>\n';
        }
    }
    $('#summary').html(html);

    $('title').html('Resmon Dashboard (' + severities[highest_sev - 1] + ')');
}

var flashtimer = null;
var flashstart = new Date().getTime();
var bgcolors = [
    '#550000',
    '#6a2c10',
    '#754706',
    '#4b400c',
    '#333333'
];
var PI = 3.1415926536;
var FLASHDURATION = 5000;

function startFlashing() {
    flashstart = new Date().getTime();
    if (!flashtimer)
        flashtimer = setInterval(updateFlash, 50);
}

function updateFlash() {
    var t = (new Date().getTime() - flashstart);
    if (t >= FLASHDURATION) {
        frac = 0;
        clearInterval(flashtimer);
        flashtimer = null;
    } else {
        var frac = Math.sin(PI * t / 1000.0);
        frac = 0.7 * (frac * frac);
    }
    for (var i = 1; i <= 5; i++) {
        var c = bgcolors[i - 1];
        var bg = '#111111';
        $('.flashing.severity-' + i).css('background-color', $.colorPercent([c, bg], frac));
    }
}

function showError() {
    $('#alerts').html('<div class="alert severity-1"><img src="/assets/icons/severity-1.png" alt=""><h2>Dashboard Error</h2><p>Error receiving status from webservice</p></div>');

    html = ''
    for (var sev = 1; sev <= 5; sev++)
        html += '<div class="summary summary-' + sev + '"><img src="/assets/icons/severity-' + sev + '.png" alt="Severity ' + sev +'">?</div>\n';
    $('#summary').html(html);
}

var POLL_INTERVAL = 6;

function poll() {
    $.ajax({
        url: '/status/json',
        dataType: "json",
        success: updatePage,
        error: showError,
    });

    setTimeout(poll, POLL_INTERVAL * 1000);
}

$(document).ready(poll);
